// axios基础的封装
import axios from 'axios'
import { useUserStore } from '@/stores/userStore'
import router from '@/router' 
const httpInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})

// 拦截器

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  //请求时从pinia中拿到用户token放在请求头中传递给后端
  const userStore = useUserStore()
  if (userStore.userInfo.token) {
    config.headers.Authorization = `Bearer ${userStore.userInfo.token}`
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
  // 统一错误提示
  ElMessage({
    type: 'warning',
    message: e.response.data.message
  })
  const userStore = useUserStore()
  //后端返回401状态码需要跳转到登录页面
  console.log(e)
  if (e.response.status === 401) {
    // 删除用户信息
    userStore.clearUserInfo()
    // 跳转到登录页面
    router.push('/login')
  }
  return Promise.reject(e)
})


export default httpInstance  